﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using Business;


public partial class Controls_BackEnd_UserGrantPermission : UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack) return;
        Attachment();
        BinderData();
        CheckPermission();
    }


    private void Attachment()
    {
        Session[SessionManager.SessionControl] = "~/Controls/BackEnd/UserFunctions.ascx";
        btnAdd.Attributes.Add("onclick", "ShowPopup(750,500,'" + Config.ApplicationUrl + "pages/popup.aspx','Chọn thêm quyền');return false;");
    }
    /// <summary>
    /// 
    /// </summary>
    private void CheckPermission()
    {

        var permission = (UserFunctions)Session[SessionManager.SessionPermission];
        btnSave.Visible = Config.Id > 0 ? permission.IsUpdate : permission.IsInsert;
        btnAdd.Visible = permission.IsInsert;
        btnRemove.Visible = permission.IsDelete;
    }

    private void BinderData()
    {
        var users = new Users { UserID = Config.Id }.Users_GetByUserID();
        ltrUser.Text = users.UserName;
        var listGrant = new UserFunctions { UserID = Config.Id }.UserFunctions_GetByUserID();
        var listAll = new Functions().Functions_GetByCondition(string.Empty);
        if (listGrant.Count <= 0)
        {
            Session[SessionManager.SessionGrant] = new List<UserFunctions>();
            Session[SessionManager.SessionList] = new List<Functions>();
            Config.NullData(new Functions(), grvData);
            btnSave.Visible = false;
            return;
        }
        Session[SessionManager.SessionGrant] = listGrant;
        Session[SessionManager.SessionList] =
            listAll.Where(functionse => listGrant.Exists(g => g.FunctionID == functionse.FunctionID)).ToList();
        grvData.DataSource = Session[SessionManager.SessionList];
        grvData.DataBind();

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void AllCommand(object sender, EventArgs e)
    {
        var index = 0;
        switch (((Control)sender).ID)
        {
            case "btnRemove":
                var listGrant = Session[SessionManager.SessionGrant] as List<UserFunctions>;
                for (index = 0; index < grvData.Rows.Count; index++)
                {
                    var key = int.Parse(grvData.DataKeys[index].Values[0].ToString());
                    foreach (var groupFunctionse in
                        listGrant.Where(groupFunctionse => key == groupFunctionse.FunctionID))
                    {
                        groupFunctionse.IsDelete =
                            (grvData.Rows[index].FindControl("cbCheckDelete") as CheckBox).Checked;
                        groupFunctionse.IsUpdate =
                            (grvData.Rows[index].FindControl("cbCheckUpdate") as CheckBox).Checked;
                        groupFunctionse.IsInsert =
                            (grvData.Rows[index].FindControl("cbInsert") as CheckBox).Checked;
                    }
                }
                var listremove = Session[SessionManager.SessionList] as List<Functions>;
                for (index = grvData.Rows.Count; index > 0; index--)
                {
                    if (!(grvData.Rows[index - 1].FindControl("cbCheck") as CheckBox).Checked) continue;
                    var grant = listGrant.Find(g => g.FunctionID == listremove[index - 1].FunctionID);
                    listGrant.Remove(grant);
                    listremove.RemoveAt(index - 1);
                }
                Session[SessionManager.SessionList] = listremove;
                Session[SessionManager.SessionGrant] = listGrant;
                grvData.DataSource = Session[SessionManager.SessionList];
                grvData.DataBind();
                break;
            case "btnBack":
                Config.Back();
                break;
            case "btnSave":
                var listsave = Session[SessionManager.SessionList] as List<Functions>;

                foreach (var functionse in listsave)
                {
                    var isDelete = (grvData.Rows[index].FindControl("cbCheckDelete") as CheckBox).Checked;
                    var isUpdate = (grvData.Rows[index].FindControl("cbCheckUpdate") as CheckBox).Checked;
                    var isInsert = (grvData.Rows[index].FindControl("cbInsert") as CheckBox).Checked;
                    new UserFunctions { CreatedTime = DateTime.Now, FunctionID = functionse.FunctionID, UserID = Config.Id, IsDelete = isDelete, IsInsert = isInsert, IsUpdate = isUpdate }.Save();
                    index++;
                }
                Config.Message(Page, Resources.Resource.SaveSuccess, Resources.Resource.Messenger);
                break;
            case "lbtnaccept":
                var list = hdfid.Value;
                var arr = list.Split('|');
                var ListFunction = (List<Functions>)Session[SessionManager.SessionListpopup];
                var listgrant = (List<UserFunctions>)Session[SessionManager.SessionGrant];
                var listFun = (List<Functions>)Session[SessionManager.SessionList];
                foreach (var s in arr)
                {
                    listFun.Add(ListFunction.Find(f => f.FunctionID == int.Parse(s)));
                    listgrant.Add(new UserFunctions { FunctionID = int.Parse(s) });
                }
                Session[SessionManager.SessionList] = listFun;
                Session[SessionManager.SessionGrant] = listgrant;
                grvData.DataSource = Session[SessionManager.SessionList];
                grvData.DataBind();
                btnSave.Visible = listgrant.Count > 0 ? true : false;
                hdfid.Value = string.Empty;
                Session.Remove(SessionManager.SessionListpopup);
                break;

        }

    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void grvData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        switch (e.Row.RowType)
        {
            case DataControlRowType.Header:
                e.Row.Cells[0].Attributes.Add("class", "first");
                e.Row.Cells[e.Row.Cells.Count - 1].Attributes.Add("class", "last");
                break;
            case DataControlRowType.DataRow:
                e.Row.Cells[1].Attributes.Add("style", "text-align:left !important;");
                var key = grvData.DataKeys[e.Row.RowIndex].Values[0];
                var list = Session[SessionManager.SessionGrant] as List<UserFunctions>;
                if (list == null || list.Count <= 0) return;
                var row = list.Find(p => p.FunctionID == int.Parse(key.ToString()));
                (e.Row.FindControl("cbInsert") as CheckBox).Checked = row.IsInsert;
                (e.Row.FindControl("cbCheckUpdate") as CheckBox).Checked = row.IsUpdate;
                (e.Row.FindControl("cbCheckDelete") as CheckBox).Checked = row.IsDelete;
                break;
            case DataControlRowType.Footer:
                break;
        }
    }

}
